import datetime
import pickle
import simplejson as json
from google.appengine.api import taskqueue
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp import util
from main import Handler, DEBUG
import models
import cheeseshop


class FreshIndexHandler(Handler):

    """Initialize the project index."""

    def get(self):
        """Fetch the project list, format appropriately, and then pass off for
        processing."""
        timestamp = datetime.datetime.utcnow()
        projects = cheeseshop.projects()[:20]
        projects_pickle = pickle.dumps(projects)
        db.run_in_transaction(self.txn, projects_pickle, timestamp)
        self.response.out.write('Enqueuing ' + str(len(projects)) +
                                ' projects')

    def txn(self, projects_pickle, timestamp):
        """Enqueue projects found at the Cheeseshop."""
        entity = models.ProjectDetails.singleton()
        entity.latest_pypi_changes = timestamp
        entity.new_projects_pickle = projects_pickle
        entity.put()
        taskqueue.add(url='/worker/create_index', transactional=True)


class WipeHandler(Handler):

    """Completely wipe all data."""

    def get(self):
        wiped_total = int(self.request.get('wiped', 0))
        wiped_now = 0
        for entity in models.Project.all().fetch(20):
            entity.delete()
            wiped_now += 1
        if wiped_now:
            wiped_total += wiped_now
            self.response.out.write('Wiped %s so far ...' % wiped_total)
            self.redirect('/admin/wipe?wiped=%s' % wiped_total)
        else:
            models.ProjectDetails.singleton().delete()
            self.response.out.write('Wiped %s projects' % wiped_total)


urls = [
        #('/admin/fresh_index', FreshIndexHandler),  # Restricted under testing
        #('/admin/wipe', WipeHandler),
       ]


def application():
    return webapp.WSGIApplication(urls, debug=DEBUG)

def main():
    util.run_wsgi_app(application())


if __name__ == '__main__':
    main()
